<?php
namespace Frieza\Modules\Decorationtask\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\DecorationTask\TaskGroup;
use Doraemon\model\MemberDecoration;
use Doraemon\tools\ImgUrl;

class TaskGroupController extends Controller
{
    use BaseController;

    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];
        if (!empty($where)) {
            $data['AND'] = $where;
        }
        return $data;
    }
    //任务列表
    public function index(Request $request,Content $content, $step =1 ){

        $request = $request->all();
        $tab = new Tab();
        $tab->addLink('阶段', '/admin/decorationtask/taskgroup/1', $step==1);
        $tab->addLink('分组', '/admin/decorationtask/taskgroup/2', $step==2);
        $tab->addLink('房屋状态', '/admin/decorationtask/taskgroup/3', $step==3);

        $request = self::_filterWhere($request);
        return $content
            ->header('装修工具任务')
            ->breadcrumb(
                ['text' => '分组管理', 'url' => '/decorationtask/taskgroup/'.$step]
            )
            ->body($tab)->row(self::listAction($request, $step));
    }

    public function listAction($request = [], $step = 1){

        $limitArr = [];
        $title = $request['AND']['group_name'];
        $category = TaskGroup::getGroupByTypeAndTital($step, $limitArr, $title, 'base');
        $categoryAll = TaskGroup::getGroupByTypeAndTital($step, [], $title, 'base');
        $gridModel = new pGridDataModel($category, count($categoryAll), [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1]
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('group_name', '分类名')->placeholder('请输入分类名');
                });
            });

            $grid->column('id')->sort();
            $grid->column('group_name', '分类名');
            $grid->column('group_type', '分组类型')->replace(['1'=>'阶段', '2'=>'标签', '3'=>'房屋状态']);
            $grid->column('group_sort', '分组排序');
            $grid->column('addtime', '添加时间');
            $grid->column('edittime', '修改时间');

            $grid->column('is_expand', '是否展开')->display(function() {
                if($this->group_type == 1) {
                    return TaskGroup::IS_EXPAND[$this->is_expand];
                } else {
                    return "——";
                }
            });
            $grid->column('is_edit_enable', '是否可添加任务/日记')->display(function() {
                if($this->group_type == 1) {
                    return TaskGroup::IS_EDIT_ENABLE[$this->is_edit_enable];
                } else {
                    return "——";
                }
            });


            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    //分组添加页面
    public function edit(Request $request,Content $content, $step, $id = 0)
    {
        $request = $request->all();

        if($id == 0) {
            return $content
                ->header('装修工具任务')
                ->breadcrumb(
                    ['text' => '一级分类管理', 'url' => '/decorationtask/taskgroup/'.$step],
                    ['text' => '添加分类', 'url' => '/decorationtask/taskgroup/'.$step.'/create']
                )
                ->body(self::editAction($step, $id , True));
        } else {
            return $content
                ->header('装修工具任务')
                ->breadcrumb(
                    ['text' => '一级分类管理', 'url' => '/decorationtask/taskgroup/'.$step],
                    ['text' => '修改分类', 'url' => '/decorationtask/taskgroup/'.$step.'/'.$id.'/edit']
                )
                ->body(self::editAction($step, $id, False));
        }

    }

    public function editAction($step, $id = 0, $isCreate = false)
    {
        if(!$isCreate) {
            //校验版本
            $data = TaskGroup::getGroupById($id);

            if($data['version'] != 0) {
                $error = new MessageBag([
                    'title' => '禁止操作 非版本0 的版本'
                ]);
                return redirect('/admin/decorationtask/taskgroup/1')->with(compact('error'));
                die;
            }
            $data['group_type_ch'] = TaskGroup::GROUP_TYPE[$data['group_type']];

            $data = self::convertTips($data);

            $form = new Form($data);
            $form->hidden('id');
            $form->hidden('group_type');
            $form->text('group_name', '分组名')->setWidth(4, 2)->required('不能为空')->help('20字以内');
            $form->text('group_type_ch', '分组类型')->setWidth(4, 2)->readonly();
            $form->number('group_sort', '分组排序')->setWidth(4, 2)->min(0)->default($data['group_sort'])->required('不能为空');
        } else {
            $data['group_type'] = $step;
            $form = new Form($data);

        }

        if($step == 1) {
            $form->text('group_desc', '阶段描述');
            $form->radio('is_expand', '是否展开')->options(TaskGroup::IS_EXPAND)->default(TaskGroup::IS_EXPAND_FALSE)->setWidth(4, 2);
            $form->radio('is_edit_enable', '是否可添加任务/日记')->options(TaskGroup::IS_EDIT_ENABLE)->default(TaskGroup::IS_EDIT_ENABLE_TRUE)->setWidth(4, 2);
        }

        $form->hidden('group_type');
        $form->text('group_name', '分组名')->setWidth(4, 2)->required('不能为空')->help('20字以内');
        $form->text('group_type_ch', '分组类型')->setWidth(4, 2)->default(TaskGroup::GROUP_TYPE[$step])->readonly();
        $form->number('group_sort', '分组排序')->setWidth(4, 2)->min(0)->required('不能为空');

        self::beforePromptTypeForm($form);
        if($step == TaskGroup::TYPE_SWARM) {
            $form->select('rela_decoration_status', '关联装修状态')->setWidth(4, 2)->options(MemberDecoration::HOUSE_MAP);
        }

        $form->action('/admin/decorationtask/taskgroup/save');

        return $form->render();
    }

    //添加、修改提交
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $data = [
            'group_name' => $request['group_name'],
            'group_type' => $request['group_type'],
            'group_desc' => (string)$request['group_desc'],
            'group_status' => TaskGroup::STATUS_NORMAL,
            'group_sort' => $request['group_sort'],
            'is_expand' => (int)$request['is_expand'],
            'is_edit_enable' => (int)$request['is_edit_enable'],
            'admin_id' => Admin::user()->id,
            'rela_decoration_status' => (int) $request['rela_decoration_status']
        ];
        //弹框提醒
        $data = self::setPromptTips($request , $data);
        if(isset($request['id'])) {
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $id = $request['id'];

            $rs = TaskGroup::edit($data, $id);
        } else {
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = TaskGroup::add($data);
        }
        if($rs) {
            if(isset($request['id'])) {
                $title = '修改成功';
            } else {
                $title = '添加成功';
            }
            $success = new MessageBag([
                'title' => $title
            ]);
            return redirect('/admin/decorationtask/taskgroup/'.$request['group_type'])->with(compact('success'));
        } else {
            if(isset($request['id'])) {
                $title = '修改失败';
            } else {
                $title = '添加失败';
            }
            $error = new MessageBag([
                'title' => $title
            ]);
            return redirect('/admin/decorationtask/taskgroup/'.$request['group_type'])->with(compact('error'));
        }
    }

    //删除
    public function del($step, $id = 0)
    {
        if($id == 1) {
            return response()->json([
                'status' => false,
                'message' => "禁止删除id为1的分类，请使用修改功能",
            ]);
            die;
        }
        $group_info = TaskGroup::getGroupById($id);
        if( $group_info['version'] != 0) {
            return response()->json([
                'status' => false,
                'message' => "禁止操作 非版本0 的版本",
            ]);
            die;
        }
        $data = [
            'group_status' => TaskGroup::STATUS_DELETE,
            'edittime' => date('Y-m-d H:i:s', time()),
            'admin_id' => Admin::user()->id
        ];
        $rs = TaskGroup::edit($data, $id);
        if($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function sort(Request $request)
    {
        $params = $request->all();
        $sort = $params['sort'];
        array_walk($sort, function(&$value, $key) {
            $value = ($value+1) * 10;
        });

        if($sort && is_array($sort)) {
            foreach($sort as $sort_key=>$sort_val) {
                $data = [
                    'group_sort' => $sort_val,
                    'admin_id' => Admin::user()->id,
                    'edittime' => date('Y-m-d H:i:s', time())
                ];
                $id = $sort_key;
                TaskGroup::edit($data, $id);
            }
        }
        return response()->json([
            'message' => "操作成功"
        ]);
    }


}